package com.xs;

import lombok.Data;

/**
 * @program: paxos-java-demo
 * @description 接受者
 * @author: wzx
 * @create: 2021-07-08 18:36
 **/
@Data
public class Acceptor {
    private String name;

    /**
     * 最后一次接收的提案
     */
    private Proposal last=new Proposal();

    public Acceptor(String name){
        this.name=name;
    }

    /**
     * 准备处理提案
     * @param proposal
     * @return
     */
    public Promise onPrepare(Proposal proposal){
        //Utils.printInfo("接受者_"+name,"准备处理",proposal.toString());
        //假设50%失败概率
        if(Math.random()>0.5)
        {
            Utils.printInfo("接受者_"+name,"onPrepare","无响应");
            return null;
        }
        if(proposal==null)
            throw new IllegalStateException("没有协议");
        //要处理的提案是最新的提案
        if(proposal.getNo()>last.getNo())
        {
            Promise response=new Promise(true,last);
            last=proposal; //结束本次提案
            Utils.printInfo("接受者_"+name,"onPrepare","接收提案");
            return response;
        }
        else{
            //不接收小于等于当前编号的Prepare请求
            Utils.printInfo("接受者_"+name,"onPrepare","拒收提案");
            return new Promise(false,null);
        }
    }

    /**
     * 接受提案
     * @param proposal
     * @return
     */
    public boolean onAccept(Proposal proposal)
    {
        if(Math.random()>0.5)
        {
            Utils.printInfo("投票者_"+name,"onAccept","无响应");
            return false;
        }
        else{
            Utils.printInfo("投票者_"+name,"onAccept","接受");
            return last.equals(proposal); //接受的提案是否提案
        }
    }


}
